package com.kkw.shoppingmall.seckill.interceptor;

import com.kkw.common.constant.AuthServerConstant;
import com.kkw.common.vo.MemberResVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Kevin
 * @date 2021-06-13
 **/
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    //ThreadLocal 同一线程上信息共享
    public static ThreadLocal<MemberResVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //解决库存调用订单服务 失败的问题
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", uri);

        if (match){
            HttpSession session = request.getSession();
            MemberResVo attribute = (MemberResVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
            if (attribute != null) {
                //说明登录了 放行
                loginUser.set(attribute);
                return true;
            } else {
                //没登录 去登录页 来拦截
                session.setAttribute("msg", "请先登录～～");
                response.sendRedirect("http://auth.shoppingmall.com/login.html");
                return false;
            }
        }
        return true;

    }
}
